package com.example.sandbox_basics;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class SQLiteActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sqlite);
	}

	public void saveData(View view) {

		EditText edittext = (EditText) findViewById(R.id.editText);
		String fullname = edittext.getText().toString();
		
		// Gets the data repository in write mode
		SQLiteDatabase db = SandboxBasicsDao.getInstance(this).getWritableDatabase();

		// Create a new map of values, where column names are the keys
		ContentValues values = new ContentValues();
		values.put(SandboxBasicsContract.PersonalData.COLUMN_NAME_PERSONAL_DATA_FULLNAME, fullname);
		values.put(SandboxBasicsContract.PersonalData.COLUMN_NAME_PERSONAL_DATA_MAIL, "my mail");

		// Insert the new row, returning the primary key value of the new row
		long newRowId;
		newRowId = db.insert(SandboxBasicsContract.PersonalData.TABLE_NAME, null, values);
		System.out.println("Registros grabados en la base de datos: " + newRowId);
	}

	public void readData(View view) {
		this.readDataFromDb();
	}
	
	private void readDataFromDb() {
		SQLiteDatabase db = SandboxBasicsDao.getInstance(this).getReadableDatabase();

		// Define a projection that specifies which columns from the database
		// you will actually use after this query.
		String[] projection = { SandboxBasicsContract.PersonalData._ID,
				SandboxBasicsContract.PersonalData.COLUMN_NAME_PERSONAL_DATA_FULLNAME,
				SandboxBasicsContract.PersonalData.COLUMN_NAME_PERSONAL_DATA_MAIL, };

		String selection = null;
		String[] selectionArgs = null;
				
		// How you want the results sorted in the resulting Cursor
		String sortOrder = SandboxBasicsContract.PersonalData._ID + " DESC";

		Cursor cursor = db.query(SandboxBasicsContract.PersonalData.TABLE_NAME, // The table to query
				projection, // The columns to return
				selection, // The columns for the WHERE clause
				selectionArgs, // The values for the WHERE clause
				null, // don't group the rows
				null, // don't filter by row groups
				sortOrder // The sort order
				);
		
		cursor.moveToFirst();
		String name = cursor.getString(cursor.getColumnIndexOrThrow(SandboxBasicsContract.PersonalData.COLUMN_NAME_PERSONAL_DATA_FULLNAME));

		EditText editText = (EditText) findViewById(R.id.editText);
		editText.setText(name);

	}
}
